﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using ZFY.AspNetCore;
using ZFY.Core;

namespace ZFY.AspNetCore
{
    public class ZFYExpectionMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly IHostingEnvironment _env;

        public ZFYExpectionMiddleware(RequestDelegate next, IHostingEnvironment env)
        {
            _next = next;
            _env = env;
        }

        // IMyScopedService is injected into Invoke
        public async Task Invoke(HttpContext httpContext)
        {
            try
            {
                await _next(httpContext);
            }
            catch (Exception ex)
            {

                await WriteExceptionResponse(httpContext, ex);

            }
        }


        private async Task WriteExceptionResponse(HttpContext context, Exception exception)
        {
            var httpResponse = context.Response;

            var zfyEx = exception as ZFYException;

            httpResponse.StatusCode = zfyEx?.StatusCode??StatusCodes.Status500InternalServerError;

            var stackTraceInfo = _env.IsDevelopment() ? exception.StackTrace : null;

            var wrapDataResult = new ZFYReponse<List<string>>()
            {
                Success = false,
                Data = new List<string>(1) { exception.Message },
                Msg = stackTraceInfo
            };

            var options = new JsonSerializerOptions
            {
                WriteIndented = true,
               
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            };

            httpResponse.ContentType =  "application/json";

            var resultJsonData = JsonSerializer.Serialize(wrapDataResult, options);
            
            await httpResponse.WriteAsync(resultJsonData, Encoding.UTF8);

        }
    }
}
